package com.lou1052.redis.jedis.action.jedis;

import com.google.common.collect.Lists;
import com.lou1052.redis.jedis.action.script.ScriptAction;
import com.lou1052.redis.jedis.api.ScriptCommands;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * 比较并替换操作 成功或者key不存在设置为新值并返回1 ，旧值不匹配返回0
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/11/14
 * Time: 20:45
 * To change this template use File | Settings | File Templates.
 */
public class ReplaceNxSetStringAction extends Action<Boolean> {

    //key 不存在返回并设置后返回2 ,cas 成功返回1 , 旧值不匹配返回0 .
    //private static final String CAS_SCRIPT = "if redis.call('exists',KEYS[1])==0 then redis.call('set',KEYS[1],ARGV[2]);return 2;elseif redis.call('get', KEYS[1])==ARGV[1] then redis.call('set',KEYS[1],ARGV[2]);return 1;else return 0;end;";
    private static final String CAS_SCRIPT = "local v=redis.call('get',KEYS[1]);if not v then redis.call('set',KEYS[1],ARGV[2]);return 2;elseif (v==ARGV[1]) then redis.call('set', KEYS[1], ARGV[2]);return 1;else return 0;end";

    private final String oldValue;

    private final String newValue;

    public ReplaceNxSetStringAction(String key, String oldValue, String newValue) {
        super(key);
        this.oldValue=oldValue;
        this.newValue=newValue;
    }



    @Override
    public Boolean callOn(Jedis jedis) {
        List<String> params = Lists.newArrayList(oldValue,newValue);
        List<String> keys = Lists.newArrayList(getKey());
        Long result= (Long)jedis.eval(CAS_SCRIPT,keys,params);
        return result>0;
    }
}
